package search.doublepointer;

/**
 * https://leetcode-cn.com/problems/volume-of-histogram-lcci/
 * 存水问题 (双指针问题）如果单边循环，不能确定下一步能存多少水
 */
public class TrapRainWater {

    public static void main(String[] args) {

        int[] nums = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
        System.out.println(new TrapRainWater().trapWater(nums));
    }

    public int trapWater(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int left = 0;
        int right = nums.length - 1;
        int leftH = nums[left];
        int rightH = nums[right];
        int sum = 0;
        while (left < right) {
            if (leftH < rightH) {
                if (leftH > nums[left + 1]) {
                    sum += leftH - nums[left + 1];
                } else {
                    leftH = nums[left + 1];
                }
                left++;
            } else {
                if (rightH > nums[right - 1]) {
                    sum += rightH - nums[right - 1];
                } else {
                    rightH = nums[right - 1];
                }
                right--;
            }
        }
        return sum;
    }
}
